// chatUI.vue
<template>
  <div class="chat-container">
    <div class="messages">
      <div
        v-for="(item, index) in chatList"
        :key="index"
        :class="['message', item.type]"
      >
        <div class="bubble">{{ item.content }}</div>
        <div class="avatar">
          <component
            :is="item.type === 'question' ? UserOutlined : RobotOutlined"
          />
        </div>
      </div>
    </div>
    <div class="input-area">
      <a-input
        v-model:value="inputValue"
        placeholder="Type a message..."
        @pressEnter="handleSend"
      />
      <a-button type="primary" @click="handleSend">send</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import axios from "axios";
import { ref } from "vue";
import { UserOutlined, RobotOutlined } from "@ant-design/icons-vue";
const inputValue = ref("");
let chatList = ref<any[]>([]);

const handleSend = () => {
  const question = inputValue.value.trim();
  if (question) {
    getAnswer(question);
    chatList.value.push({ type: "question", content: question });
    inputValue.value = ""; // 清空输入框
  }
};
function getAnswer(question: string) {
  const URL = "http://localhost:8081/chat";
  const payload = {
    messages: question,
  };
  sendPost(
    URL,
    payload,
    {},
    (res: any) => {
      console.log(res.data.message);
      chatList.value.push({ type: "answer", content: res.data.message });
    },
    (err: any) => {
      console.log(err);
    }
  );
}

//post方法
function sendPost(
  url: string,
  data: any,
  headers = {},
  funcSuccess: any,
  funcError: any
) {
  const headerTem = {
    "content-Type": "application/json;charset=UTF-8",
  };
  if (JSON.stringify(headers) != "{}") {
    Object.assign(headerTem, headers);
  }
  axios
    .post(url, data, {
      headers: headerTem,
    })
    .then(function (res) {
      console.log("sendPost res info :", res);
      funcSuccess(res);
    })
    .catch((err) => {
      console.log("sendPost err info :" + err);
      if (funcError) {
        funcError(err);
      }
    });
}
</script>

<style scoped>
.chat-container {
  min-width: 300px;
  height: 100%;
  display: flex;
  flex-direction: column;
  /* background-color: #1e1e1e; */
  border: 1px solid #999;
  border-radius: 8px;
}

.messages {
  height: 650px;
  overflow-y: auto;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.bubble {
  color: #333;
  text-align: right;
  margin-right: 8px;
}
.input-area {
  display: flex;
}
.message {
  display: flex;
  align-items: center;
}

.question {
  justify-content: flex-end;
}

.answer {
  justify-content: flex-start;
}
</style>

